//
//  KeyboardResponder.swift
//  WeiBoDemo
//
//  Created by chaowen deng on 2021/3/26.
//

import SwiftUI


class KeyboardResponder: ObservableObject {
    
    @Published var keyboardHeight: CGFloat = 0
    
    var keyboardShow: Bool { keyboardHeight > 0 }
    
    init() {
        // 键盘即将弹出时 的通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_ :)), name: UIWindow.keyboardWillShowNotification, object: nil)
        // 键盘即将隐藏的 通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIWindow.keyboardWillHideNotification, object: nil)
    }
    
    deinit { NotificationCenter.default.removeObserver(self) }
    
    @objc private func keyboardWillShow(_ notionfication: Notification) {
        guard let frame = notionfication.userInfo?[UIWindow.keyboardFrameEndUserInfoKey] as? CGRect else {
            return
        }
        
        keyboardHeight = frame.height
    }
    
    @objc private func keyboardWillHide(_ notionfication: Notification) {
        keyboardHeight = 0
    }
}
